package com.tiancikeji.zaoke.app.common.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.tiancikeji.zaoke.app.model.order.Bill;
import com.tiancikeji.zaoke.app.service.bill.BillService;

public class AlipayWebGoBackServlet extends HttpServlet {
	
	private static final long serialVersionUID = -1719974023916899268L;

	private Log logger = LogFactory.getLog(getClass());

    private BillService billService;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			String result = goback(req.getParameter("serialId"));
			String url = "http://zaoke.me/order_success.html?orderid=" + result;
			resp.sendRedirect(url);
		} catch (Throwable e) {
			logger.error("Something wrong when invoke AlipayWapCallbackServlet callback method", e);
		}
	}
    
	public String goback(String serialId) {
		if (StringUtils.isNotBlank(serialId)) {

			Bill bill = getBillService().getBillBySerialId(serialId);

			if (bill != null && bill.getStatus() == bill.getStatus())
				return bill.getTrace();
		}

		return StringUtils.EMPTY;
	}

	public BillService getBillService() {
		return WebApplicationContextUtils.getWebApplicationContext(getServletContext()).getBean("alipayWapGoBackServlet", getClass()).billService;
	}

	public void setBillService(BillService billService) {
		this.billService = billService;
	}
}
